package com.zbkj.admin.task.safe;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.qcloud.cos.utils.UrlEncoderUtils;
import com.zbkj.admin.service.SafeDeptService;
import com.zbkj.admin.service.SafeEnterpriseService;
import com.zbkj.admin.service.SafeService;
import com.zbkj.admin.service.SafeUserService;
import com.zbkj.admin.task.product.ProductStockTask;
import com.zbkj.common.config.CrmebConfig;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.model.safe.SafeDept;
import com.zbkj.common.model.safe.SafeEnterprise;
import com.zbkj.common.model.safe.SafeRecord;
import com.zbkj.common.model.safe.SafeUser;
import com.zbkj.common.model.sms.SmsRecord;
import com.zbkj.common.model.system.SystemAttachment;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.common.utils.ExportUtil;
import com.zbkj.service.service.SmsRecordService;
import com.zbkj.service.service.SystemAttachmentService;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Configuration //读取配置
@EnableScheduling // 2.开启定时任务
public class SafeTask {

    private static final Logger logger = LoggerFactory.getLogger(SafeTask.class);


    @Autowired
    private SafeService safeService;

    @Autowired
    private SafeEnterpriseService enterpriseService;
    @Autowired
    private SafeUserService safeUserService;

    @Autowired
    private SmsRecordService smsRecordService;

    @Autowired
    private SafeDeptService safeDeptService;
    @Autowired
    private CrmebConfig crmebConfig;

    @Autowired
    private SystemAttachmentService attachmentService;

//        @Scheduled(cron = "0 0 8 * * ?")
//    @Scheduled(fixedDelay = 1000 * 3600L)
    public void init() {
        sendSms();
    }

    private Map<String, List<SafeRecord>> sendDangerSmsNew(String cityCode, String token) {
        Map<String, List<SafeRecord>> recordMap=new HashMap<>();

        LambdaQueryWrapper<SafeEnterprise> lqw=new LambdaQueryWrapper<>();
        lqw.likeRight(SafeEnterprise::getCityCode,cityCode);
        lqw.eq(SafeEnterprise::getIsDelete,false);
        List<SafeEnterprise> enterprises = enterpriseService.list(lqw);
        for(int i=0;i<enterprises.size();i++){
            SafeEnterprise enterprise=enterprises.get(i);
            int page = 1;
            List<SafeRecord> safeRecords = new ArrayList<>();
            JSONObject dangerResult = new JSONObject(safeService.dangerSafeRecord(30, page, 0,3, 3, token,enterprise.getEntFullName()));
            safeRecords.addAll(JSONArray.parseArray(
                    dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
            while (dangerResult.getJSONArray("records").size() == 10) {
                page++;
                dangerResult = new JSONObject(safeService.dangerSafeRecord(30, page, 0,3, 3, token,enterprise.getEntFullName()));
                safeRecords.addAll(JSONArray.parseArray(
                        dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
            }
            if(CollectionUtil.isNotEmpty(safeRecords)){

            }
        }
        return recordMap;
    }

    /**
     * @param cityCode
     * @param token
     * @return map<key:企业id ， value:企业未隐患>
     */
    private Map<String, List<SafeRecord>> sendDangerSms(String cityCode, String token) {
        int page = 1;
        List<SafeRecord> safeRecords = new ArrayList<>();
        JSONObject dangerResult = new JSONObject(safeService.dangerSafeRecordOld(30, page, 3, 3, token,null));
        safeRecords.addAll(JSONArray.parseArray(
                dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
        while (dangerResult.getJSONArray("records").size() == 10) {
            page++;
            dangerResult = new JSONObject(safeService.dangerSafeRecordOld(30, page, 3, 3, token,null));
            safeRecords.addAll(JSONArray.parseArray(
                    dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
        }
        LambdaQueryWrapper<SafeEnterprise> lqw=new LambdaQueryWrapper<>();
        lqw.likeRight(SafeEnterprise::getCityCode,cityCode);
        lqw.eq(SafeEnterprise::getIsDelete,false);
        List<SafeEnterprise> enterprises = enterpriseService.list(lqw);
        Map<String, SafeEnterprise> enterpriseMap = enterprises
                .stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        if (CollectionUtil.isNotEmpty(safeRecords)) {
            SafeDept dept=safeDeptService.getParent(safeRecords.get(0).getProdAddrCode());
            //发送第3天未整改短信
            List<SmsRecord> smsRecords = new ArrayList<>();
            Map<String, List<SafeRecord>> recordMap = safeRecords.stream().collect(Collectors.groupingBy(SafeRecord::getEntId));
            for (Map.Entry<String, List<SafeRecord>> entry : recordMap.entrySet()) {
                SafeEnterprise safeEnterprise = enterpriseMap.get(entry.getKey());
                if (ObjectUtil.isEmpty(safeEnterprise)) {
                    continue;
                }
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(2);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(safeEnterprise.getEntFullName());
                smsRecord.setEntId(safeEnterprise.getEntId());
                smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                smsRecord.setContent("【工业企业安全在线】" + safeEnterprise.getEntFullName() + ",您公司在工业安全在线系统的未整改隐患于"
                        + entry.getValue().get(0).getNeatenLimitDate()
                        + "到期，请在有限期内完成相应工作。"
                        + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                        + "应急管理所("+dept.getExtend03()+")");
                smsRecord.setUsername(safeEnterprise.getPrincipal());
                smsRecord.setSended(false);
                smsRecords.add(smsRecord);
            }
            safeService.removeTodaySendSmsPhone(smsRecords, 2);
            if (CollectionUtil.isNotEmpty(smsRecords)) {
                smsRecords.forEach(smsRecord -> {
//                    smsRecord.setResultStr(safeService.sendSms(smsRecord.getPhone(), smsRecord.getContent()));
                });
                smsRecordService.saveBatch(smsRecords);
            }
        }
        //整改期限小于等于2天的
        safeRecords.clear();
        page = 1;
        dangerResult = new JSONObject(safeService.dangerSafeRecordOld(30, page, 0, -2, token,null));
        safeRecords.addAll(JSONArray.parseArray(
                dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
        while (dangerResult.getJSONArray("records").size() == 10) {
            page++;
            dangerResult = new JSONObject(safeService.dangerSafeRecordOld(30, page, 0, -2, token,null));
            safeRecords.addAll(JSONArray.parseArray(
                    dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
        }
        if (CollectionUtil.isNotEmpty(safeRecords)) {
            List<SmsRecord> smsRecords = new ArrayList<>();
            SafeDept dept=safeDeptService.getParent(safeRecords.get(0).getProdAddrCode());

            Map<String, List<SafeRecord>> recordMap = safeRecords.stream().collect(Collectors.groupingBy(SafeRecord::getEntId));
            for (Map.Entry<String, List<SafeRecord>> entry : recordMap.entrySet()) {
                SafeEnterprise safeEnterprise = enterpriseMap.get(entry.getKey());
                if (ObjectUtil.isEmpty(safeEnterprise)) {
                    continue;
                }
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(2);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(safeEnterprise.getEntFullName());
                smsRecord.setEntId(safeEnterprise.getEntId());
                smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                smsRecord.setContent("【工业企业安全在线】" + safeEnterprise.getEntFullName()
                        + ",您公司在工业安全在线系统的未整改隐患于" + entry.getValue().get(0).getNeatenLimitDate()
                        + "到期，请在有限期内完成相应工作。"
                        + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                        + "应急管理所("+dept.getExtend03()+")");
                smsRecord.setUsername(safeEnterprise.getPrincipal());
                smsRecord.setSended(false);
                smsRecords.add(smsRecord);
            }
            safeService.removeTodaySendSmsPhone(smsRecords, 2);
            if (CollectionUtil.isNotEmpty(smsRecords)) {
                smsRecords.forEach(smsRecord -> {
//                    smsRecord.setResultStr(safeService.sendSms(smsRecord.getPhone(), smsRecord.getContent()));
                });
                smsRecordService.saveBatch(smsRecords);
            }

            if (CollectionUtil.isEmpty(recordMap)
                    || CollectionUtil.isNotEmpty(recordMap)) {
                return recordMap;
            }
        } else {
            return new HashMap<>();
        }
        return new HashMap<>();
    }

    private List<SafeEnterprise> sendSelfCheckSms(String cityCode, String token) {
        Date date27 = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -27));
        Date date28 = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -28));
        Date startDateMonth=DateUtil.beginOfMonth(new Date());
        LambdaQueryWrapper<SafeEnterprise> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SafeEnterprise::getIsDelete, false);
        lqw.likeRight(SafeEnterprise::getCityCode,cityCode);
        List<SafeEnterprise> enterprises = enterpriseService.list(lqw);
        if (CollectionUtil.isEmpty(enterprises)) {
            return enterprises;
        }
        List<SafeEnterprise> safeEnterprises27 = new ArrayList<>();
        List<SafeEnterprise> safeEnterprises28 = new ArrayList<>();
        List<SafeEnterprise> safeEnterpriseMonth = new ArrayList<>();
        List<SmsRecord> smsRecords = new ArrayList<>();
        enterprises.forEach(safeEnterprise -> {
            SafeDept dept=safeDeptService.getParent(safeEnterprise.getCityCode());

            if (ObjectUtil.isNotEmpty(safeEnterprise.getSelfCheckDate())
            &&safeEnterprise.getSelfCheckDate().equals(date27)) {
                safeEnterprises27.add(safeEnterprise);
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(3);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(safeEnterprise.getEntFullName());
                smsRecord.setEntId(safeEnterprise.getEntId());
                smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                smsRecord.setContent("【工业企业安全在线】" + safeEnterprise.getEntFullName() + ",您公司在还未完成当月企业自查，请在有限期内完成相应工作。"
                        + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                        + "应急管理所("+dept.getExtend03()+")");
                smsRecord.setUsername(safeEnterprise.getPrincipal());
                smsRecord.setSended(false);
                smsRecords.add(smsRecord);
                safeEnterpriseMonth.add(safeEnterprise);
            }
            if (ObjectUtil.isNotEmpty(safeEnterprise.getSelfCheckDate())
            &&safeEnterprise.getSelfCheckDate().compareTo(date28) <= 0) {
                safeEnterprises28.add(safeEnterprise);
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(3);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(safeEnterprise.getEntFullName());
                smsRecord.setEntId(safeEnterprise.getEntId());
                smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                String deadLineStr = DateUtil.format(DateUtil.offsetDay(safeEnterprise.getSelfCheckDate(), 30), "yyyy-MM-dd");
                smsRecord.setContent("【工业企业安全在线】" + safeEnterprise.getEntFullName()
                        + ",您公司在工业安全在线系统的隐患企业自查于" + deadLineStr
                        + "到期，请在有限期内完成相应工作。"
                        + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                        + "应急管理所("+dept.getExtend03()+")");
                smsRecord.setUsername(safeEnterprise.getPrincipal());
                smsRecord.setSended(false);
                smsRecords.add(smsRecord);
            }
            if(ObjectUtil.isEmpty(safeEnterprise.getSelfCheckDate())){
                safeEnterpriseMonth.add(safeEnterprise);
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(3);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(safeEnterprise.getEntFullName());
                smsRecord.setEntId(safeEnterprise.getEntId());
                smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                smsRecord.setContent("【工业企业安全在线】" + safeEnterprise.getEntFullName()
                        + ",您公司在工业安全在线系统的隐患企业自查本月还未完成，请在有限期内完成相应工作。"
                        + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                        + "应急管理所("+dept.getExtend03()+")");
                smsRecord.setUsername(safeEnterprise.getPrincipal());
                smsRecord.setSended(false);
                smsRecords.add(smsRecord);
            }
        });
        System.out.println(smsRecords);
        safeService.removeTodaySendSmsPhone(smsRecords, 3);
        smsRecords.forEach(smsRecord -> {
//            smsRecord.setResultStr(safeService.sendSms(smsRecord.getPhone(), smsRecord.getContent()));
        });
        smsRecordService.saveBatch(smsRecords);


        //通知街道管理员
        if (CollectionUtil.isEmpty(safeEnterpriseMonth)
                || CollectionUtil.isNotEmpty(safeEnterpriseMonth)) {
            return safeEnterpriseMonth;
        } else {

        }


        return safeEnterpriseMonth;
    }


    private List<SafeEnterprise> sendCpcxSms(String cityCode, String token) {
        Date date87 = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -87));
        Date date88 = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -88));
        LambdaQueryWrapper<SafeEnterprise> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SafeEnterprise::getIsDelete, false);
        lqw.likeRight(SafeEnterprise::getCityCode,cityCode);
        List<SafeEnterprise> enterprises = enterpriseService.list(lqw);
        if (CollectionUtil.isEmpty(enterprises)) {
            return enterprises;
        }
        List<SafeEnterprise> safeEnterprises87 = new ArrayList<>();
        List<SafeEnterprise> safeEnterprises88 = new ArrayList<>();
        List<SmsRecord> smsRecords = new ArrayList<>();
        enterprises.forEach(safeEnterprise -> {
            SafeDept dept=safeDeptService.getParent(safeEnterprise.getCityCode());
            if(ObjectUtil.isEmpty(safeEnterprise.getLastOftencheckDate())){
                safeEnterprises87.add(safeEnterprise);
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(1);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(safeEnterprise.getEntFullName());
                smsRecord.setEntId(safeEnterprise.getEntId());
                smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                smsRecord.setContent("【工业企业安全在线】" + safeEnterprise.getEntFullName()
                        + ",您公司在工业安全在线系统的常普常新(风险普查)还未完成"
                       + "，请在有限期内完成相应工作。"
                        + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                        + "应急管理所 ("+dept.getExtend03()+")");
                smsRecord.setUsername(safeEnterprise.getPrincipal());
                smsRecord.setSended(false);
                smsRecords.add(smsRecord);
            }else{
                if (safeEnterprise.getLastOftencheckDate().equals(date87)) {
                    safeEnterprises87.add(safeEnterprise);
                    SmsRecord smsRecord = new SmsRecord();
                    smsRecord.setType(1);
                    smsRecord.setCreateTime(new Date());
                    smsRecord.setEntName(safeEnterprise.getEntFullName());
                    smsRecord.setEntId(safeEnterprise.getEntId());
                    smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                    String deadLineStr = DateUtil.format(DateUtil.offsetDay(safeEnterprise.getLastOftencheckDate(), 90), "yyyy-MM-dd");
                    smsRecord.setContent("【工业企业安全在线】" + safeEnterprise.getEntFullName()
                            + ",您公司在工业安全在线系统的常普常新(风险普查)于"
                            + deadLineStr + "到期，请在有限期内完成相应工作。"
                            + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                            + "应急管理所 ("+dept.getExtend03()+")");
                    smsRecord.setUsername(safeEnterprise.getPrincipal());
                    smsRecord.setSended(false);
                    smsRecords.add(smsRecord);
                }
                if (safeEnterprise.getLastOftencheckDate().compareTo(date88) <= 0) {
                    safeEnterprises88.add(safeEnterprise);
                    SmsRecord smsRecord = new SmsRecord();
                    smsRecord.setType(1);
                    smsRecord.setCreateTime(new Date());
                    smsRecord.setEntName(safeEnterprise.getEntFullName());
                    smsRecord.setEntId(safeEnterprise.getEntId());
                    smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                    String deadLineStr = DateUtil.format(DateUtil.offsetDay(safeEnterprise.getLastOftencheckDate(), 90), "yyyy-MM-dd");
                    smsRecord.setContent("【工业企业安全在线】"
                            + safeEnterprise.getEntFullName()
                            + ",您公司在工业安全在线系统的常普常新(风险普查)于"
                            + deadLineStr + "到期，请在有限期内完成相应工作。"
                            + safeEnterprise.getCityName().replace("宁波国家高新区", "").replace("浙江省","").replace("宁波市","")
                            + "应急管理所("+dept.getExtend03()+")");
                    smsRecord.setUsername(safeEnterprise.getPrincipal());
                    smsRecord.setSended(false);
                    smsRecords.add(smsRecord);
                }
            }

        });
        System.out.println(smsRecords);
        safeService.removeTodaySendSmsPhone(smsRecords, 1);
        smsRecords.forEach(smsRecord -> {
//            smsRecord.setResultStr(safeService.sendSms(smsRecord.getPhone(), smsRecord.getContent()));
        });
        smsRecordService.saveBatch(smsRecords);


        //通知街道管理员
        if (CollectionUtil.isEmpty(safeEnterprises88) || CollectionUtil.isNotEmpty(safeEnterprises88)) {
            return safeEnterprises88;
        }
        return safeEnterprises88;

    }


    public void sendSms() {
        List<SafeDept> safeDepts = safeDeptService.getChildrenDeptTree("3302").get(0).getChildren();
        LambdaQueryWrapper<SafeEnterprise> lqw=new LambdaQueryWrapper<>();
        lqw.eq(SafeEnterprise::getIsDelete,false);
        List<SafeEnterprise> enterprises = enterpriseService.list(lqw);
        Map<String, SafeEnterprise> enterpriseMap = enterprises
                .stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        safeDepts.forEach(dept -> {
            if (dept.getSendSms()) {
                //区和街道都发送的一级
                String token = dept.getToken();
                Map<String, List<SafeRecord>> recordMap = sendDangerSms(dept.getExtend02(), token);
                List<SafeEnterprise> selfCheckEntList = sendSelfCheckSms(dept.getExtend02(), token);
                List<SafeEnterprise> cpcxEntList = sendCpcxSms(dept.getExtend02(), token);
                sendGovSms(dept, selfCheckEntList, cpcxEntList, recordMap, "area",enterpriseMap);
                dept.getChildren().forEach(child->{
                    sendGovSms(child,selfCheckEntList,cpcxEntList,recordMap,"street",enterpriseMap);
                });
            } else {
                //仅街道一级发送
                dept.getChildren().forEach(streetDept -> {
                    if (streetDept.getSendSms()) {
                        String token = streetDept.getToken();
                        Map<String, List<SafeRecord>> recordMap = sendDangerSms(streetDept.getExtend02(), token);
                        List<SafeEnterprise> selfCheckEntList = sendSelfCheckSms(streetDept.getExtend02(), token);
                        List<SafeEnterprise> cpcxEntList = sendCpcxSms(streetDept.getExtend02(), token);
                        sendGovSms(streetDept, selfCheckEntList, cpcxEntList, recordMap, "street",enterpriseMap);
                    }
                });
            }

        });
    }

    private void sendGovSms(SafeDept areaDept, List<SafeEnterprise> selfCheckEntList, List<SafeEnterprise> cpcxEntList
            , Map<String, List<SafeRecord>> dangerRecordListMap, String type
            ,Map<String,SafeEnterprise> enterpriseMap) {
        LambdaQueryWrapper<SafeUser> safeUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        safeUserLambdaQueryWrapper.eq(SafeUser::getSendSms, true);
        List<SafeUser> safeUsers = safeUserService.list(safeUserLambdaQueryWrapper);
        Map<String, List<SafeUser>> deptUserMap = safeUsers.stream()
                .collect(Collectors.groupingBy(SafeUser::getCityCode));
        if (type.equals("area")) {
            ExportUtil.setUpload(crmebConfig.getImagePath(), Constants.UPLOAD_MODEL_PATH_EXCEL, Constants.UPLOAD_TYPE_FILE);

            // 文件名
            String fileName = areaDept.getExtend02()
                    .concat(com.zbkj.common.utils.DateUtil.nowDateTime(Constants.DATE_TIME_FORMAT_NUM)).concat(CrmebUtil.randomCount(111111111, 999999999).toString()).concat(".xlsx");
            LinkedHashMap<String, String> aliasMap = new LinkedHashMap<>();
            aliasMap.put("entFullName", "企业名称");
            aliasMap.put("cityName", "行政区域");
            aliasMap.put("industryTypeName", "所属行业");
            aliasMap.put("principal", "负责人");
            aliasMap.put("principalMphone", "联系电话");
            aliasMap.put("selfCheckDate", "自查时间");
            aliasMap.put("selfCheckCount", "当月自查隐患数量");
            List<JSONObject> entJsonList = new ArrayList<>();
            selfCheckEntList.forEach(safeEnterprise -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("entFullName", safeEnterprise.getEntFullName());
                jsonObject.put("cityName", safeEnterprise.getCityName());
                jsonObject.put("industryTypeName", safeEnterprise.getIndustryTypeName());
                jsonObject.put("principal", safeEnterprise.getPrincipal());
                jsonObject.put("principalMphone", safeEnterprise.getPrincipalMphone());
                jsonObject.put("selfCheckDate", safeEnterprise.getSelfCheckDate());
                jsonObject.put("selfCheckCount", safeEnterprise.getSelfCheckCount());
                entJsonList.add(jsonObject);
            });
            String lastFileName=ExportUtil.exportExecl(fileName, "自查企业提醒", entJsonList, aliasMap, "自查企业");
            //写入常普常新
            LinkedHashMap<String, String> aliasCpcxMap = new LinkedHashMap<>();
            aliasCpcxMap.put("entFullName", "企业名称");
            aliasCpcxMap.put("cityName", "行政区域");
            aliasCpcxMap.put("industryTypeName", "所属行业");
            aliasCpcxMap.put("principal", "负责人");
            aliasCpcxMap.put("principalMphone", "联系电话");
            aliasCpcxMap.put("lastOftencheckDate", "常普常新时间");
            List<JSONObject> entCpcxJsonList = new ArrayList<>();
            cpcxEntList.forEach(safeEnterprise -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("entFullName", safeEnterprise.getEntFullName());
                jsonObject.put("cityName", safeEnterprise.getCityName());
                jsonObject.put("industryTypeName", safeEnterprise.getIndustryTypeName());
                jsonObject.put("principal", safeEnterprise.getPrincipal());
                jsonObject.put("principalMphone", safeEnterprise.getPrincipalMphone());
                jsonObject.put("lastOftencheckDate", safeEnterprise.getLastOftencheckDate());
                entCpcxJsonList.add(jsonObject);
            });
            ExportUtil.exportExecl(fileName, "常普常新企业提醒", entCpcxJsonList, aliasCpcxMap, "常普常新");

            //写入 隐患信息
            LinkedHashMap<String, String> aliasDangerMap = new LinkedHashMap<>();
            aliasDangerMap.put("hdDesc", "隐患描述");
            aliasDangerMap.put("entFullName", "企业名称");
            aliasDangerMap.put("principal", "负责人");
            aliasDangerMap.put("principalMphone", "联系电话");
            aliasDangerMap.put("checkTime", "排查日期");
            aliasDangerMap.put("hdLevelName", "隐患等级");
            aliasDangerMap.put("prodAddrName", "行政区划");
            aliasDangerMap.put("industryTypeName", "行业类别");
            aliasDangerMap.put("neatenLimitDate", "整改期限");
            aliasDangerMap.put("hdSourceName", "隐患来源");
            List<JSONObject> entDangerJsonList = new ArrayList<>();
            for (String key : dangerRecordListMap.keySet()) {
                List<SafeRecord> records=dangerRecordListMap.get(key);
                records.forEach(record->{
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("hdDesc", record.getHdDesc());
                    jsonObject.put("entFullName", record.getEntFullName());
                    jsonObject.put("principal", enterpriseMap.get(record.getEntId()).getPrincipal());
                    jsonObject.put("principalMphone", enterpriseMap.get(record.getEntId()).getPrincipalMphone());
                    jsonObject.put("checkTime", record.getCheckTime());
                    jsonObject.put("hdLevelName", record.getHdLevelName());
                    jsonObject.put("prodAddrName",record.getProdAddrName());
                    jsonObject.put("industryTypeName", record.getIndustryTypeName());
                    jsonObject.put("neatenLimitDate", record.getNeatenLimitDate());
                    jsonObject.put("hdSourceName", record.getHdSourceName());
                    entDangerJsonList.add(jsonObject);
                });
            }

            ExportUtil.exportExecl(fileName, "隐患提醒", entDangerJsonList, aliasDangerMap, "隐患提醒");


            //发送区管理员提醒短信
            List<SafeUser> users = deptUserMap.get(areaDept.getExtend02());
            List<SmsRecord> smsRecords=new ArrayList<>();
            if (CollectionUtil.isNotEmpty(users)) {
                users.forEach(user -> {
                    SystemAttachment systemAttachment=new SystemAttachment();
                    systemAttachment.setSattDir(lastFileName);
                    systemAttachment.setPid(0);
                    systemAttachment.setImageType(1);
                    systemAttachment.setAttType("excel");
                    systemAttachment.setAttSize("111");
                    systemAttachment.setName(lastFileName.substring(lastFileName.lastIndexOf("/")+1));
                    attachmentService.save(systemAttachment);
                    String content = "【工业企业安全在线】,您所在的"
                            + user.getDeptFullName() +
                            "统计下载："+"http://safe360.top:21001/safe/down?fId="+systemAttachment.getAttId();
                    SmsRecord smsRecord = new SmsRecord();
                    smsRecord.setType(4);
                    smsRecord.setCreateTime(new Date());
                    smsRecord.setEntName(user.getDeptFullName());
                    smsRecord.setEntId(areaDept.getExtend02());
                    smsRecord.setPhone(user.getPhone());
                    smsRecord.setUsername(user.getPersonName());
                    smsRecord.setContent(content);
                    smsRecord.setSended(false);
                    smsRecords.add(smsRecord);
                });
            }
            safeService.removeTodaySendSmsPhone(smsRecords, 4);
            smsRecords.forEach(smsRecord -> {
//                smsRecord.setResultStr(safeService.sendSms(smsRecord.getPhone(), smsRecord.getContent()));
            });
            smsRecordService.saveBatch(smsRecords);
        }
        if (type.equals("street")) {
            ExportUtil.setUpload(crmebConfig.getImagePath(), Constants.UPLOAD_MODEL_PATH_EXCEL
                    , Constants.UPLOAD_TYPE_FILE);

            // 文件名
            String fileName = areaDept.getExtend02()
                    .concat(com.zbkj.common.utils.DateUtil.nowDateTime(Constants.DATE_TIME_FORMAT_NUM)).concat(CrmebUtil.randomCount(111111111, 999999999).toString()).concat(".xlsx");
            LinkedHashMap<String, String> aliasMap = new LinkedHashMap<>();
            aliasMap.put("entFullName", "企业名称");
            aliasMap.put("cityName", "行政区域");
            aliasMap.put("industryTypeName", "所属行业");
            aliasMap.put("principal", "负责人");
            aliasMap.put("principalMphone", "联系电话");
            aliasMap.put("selfCheckDate", "自查时间");
            aliasMap.put("selfCheckCount", "当月自查隐患数量");
            List<JSONObject> entJsonList = new ArrayList<>();
            selfCheckEntList.forEach(safeEnterprise -> {
                if(safeEnterprise.getCityCode().equals(areaDept.getExtend02())){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("entFullName", safeEnterprise.getEntFullName());
                    jsonObject.put("cityName", safeEnterprise.getCityName());
                    jsonObject.put("industryTypeName", safeEnterprise.getIndustryTypeName());
                    jsonObject.put("principal", safeEnterprise.getPrincipal());
                    jsonObject.put("principalMphone", safeEnterprise.getPrincipalMphone());
                    jsonObject.put("selfCheckDate", safeEnterprise.getSelfCheckDate());
                    jsonObject.put("selfCheckCount",safeEnterprise.getSelfCheckCount());
                    entJsonList.add(jsonObject);
                }
            });
            String lastFileName=ExportUtil
                    .exportExecl(fileName, "自查企业提醒", entJsonList, aliasMap, "自查企业");
            //写入常普常新
            LinkedHashMap<String, String> aliasCpcxMap = new LinkedHashMap<>();
            aliasCpcxMap.put("entFullName", "企业名称");
            aliasCpcxMap.put("cityName", "行政区域");
            aliasCpcxMap.put("industryTypeName", "所属行业");
            aliasCpcxMap.put("principal", "负责人");
            aliasCpcxMap.put("principalMphone", "联系电话");
            aliasCpcxMap.put("lastOftencheckDate", "常普常新时间");
            List<JSONObject> entCpcxJsonList = new ArrayList<>();
            cpcxEntList.forEach(safeEnterprise -> {
                if(safeEnterprise.getCityCode().equals(areaDept.getExtend02())){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("entFullName", safeEnterprise.getEntFullName());
                    jsonObject.put("cityName", safeEnterprise.getCityName());
                    jsonObject.put("industryTypeName", safeEnterprise.getIndustryTypeName());
                    jsonObject.put("principal", safeEnterprise.getPrincipal());
                    jsonObject.put("principalMphone", safeEnterprise.getPrincipalMphone());
                    jsonObject.put("lastOftencheckDate", safeEnterprise.getLastOftencheckDate());
                    entCpcxJsonList.add(jsonObject);
                }
            });
            ExportUtil.exportExecl(fileName
                    , "常普常新企业提醒", entCpcxJsonList, aliasCpcxMap, "常普常新");

            //写入 隐患信息
            LinkedHashMap<String, String> aliasDangerMap = new LinkedHashMap<>();
            aliasDangerMap.put("hdDesc", "隐患描述");
            aliasDangerMap.put("entFullName", "企业名称");
            aliasDangerMap.put("principal", "负责人");
            aliasDangerMap.put("principalMphone", "联系电话");
            aliasDangerMap.put("checkTime", "排查日期");
            aliasDangerMap.put("hdLevelName", "隐患等级");
            aliasDangerMap.put("prodAddrName", "行政区划");
            aliasDangerMap.put("industryTypeName", "行业类别");
            aliasDangerMap.put("neatenLimitDate", "整改期限");
            aliasDangerMap.put("hdSourceName", "隐患来源");
            List<JSONObject> entDangerJsonList = new ArrayList<>();
            for (String key : dangerRecordListMap.keySet()) {
                List<SafeRecord> records=dangerRecordListMap.get(key);
                records.forEach(record->{
                    if(record.getProdAddrCode().equals(areaDept.getExtend02())){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("hdDesc", record.getHdDesc());
                        jsonObject.put("entFullName", record.getEntFullName());
                        jsonObject.put("principal", enterpriseMap.get(record.getEntId()).getPrincipal());
                        jsonObject.put("principalMphone", enterpriseMap.get(record.getEntId()).getPrincipalMphone());
                        jsonObject.put("checkTime", record.getCheckTime());
                        jsonObject.put("hdLevelName", record.getHdLevelName());
                        jsonObject.put("prodAddrName",record.getProdAddrName());
                        jsonObject.put("industryTypeName", record.getIndustryTypeName());
                        jsonObject.put("neatenLimitDate", record.getNeatenLimitDate());
                        jsonObject.put("hdSourceName", record.getHdSourceName());
                        entDangerJsonList.add(jsonObject);
                    }
                });
            }

            ExportUtil.exportExecl(fileName, "隐患提醒", entDangerJsonList, aliasDangerMap, "隐患提醒");


            //发送区管理员提醒短信
            List<SafeUser> users = deptUserMap.get(areaDept.getExtend02());
            List<SmsRecord> smsRecords=new ArrayList<>();
            if (CollectionUtil.isNotEmpty(users)) {
                users.forEach(user -> {
                    SystemAttachment systemAttachment=new SystemAttachment();
                    systemAttachment.setSattDir(lastFileName);
                    systemAttachment.setPid(0);
                    systemAttachment.setImageType(1);
                    systemAttachment.setAttType("excel");
                    systemAttachment.setAttSize("111");
                    systemAttachment.setName(lastFileName.substring(lastFileName.lastIndexOf("/")+1));
                    attachmentService.save(systemAttachment);
                    String content = "【工业企业安全在线】,您所在的"
                            + user.getDeptFullName() +
                            "统计下载："+"http://safe360.top:21001/safe/down?fId="+systemAttachment.getAttId();
                    SmsRecord smsRecord = new SmsRecord();
                    smsRecord.setType(5);
                    smsRecord.setCreateTime(new Date());
                    smsRecord.setEntName(user.getDeptFullName());
                    smsRecord.setEntId(areaDept.getExtend02());
                    smsRecord.setPhone(user.getPhone());
                    smsRecord.setUsername(user.getPersonName());
                    smsRecord.setContent(content);
                    smsRecord.setSended(false);
                    smsRecords.add(smsRecord);
                });
            }
            safeService.removeTodaySendSmsPhone(smsRecords, 5);
            smsRecords.forEach(smsRecord -> {
//                smsRecord.setResultStr(safeService.sendSms(smsRecord.getPhone(), smsRecord.getContent()));
            });
            smsRecordService.saveBatch(smsRecords);
        }

    }

    public static void main(String[] args) {
     String name="https://safe360.top/img/crmebimage/file/excel/2022/11/14/工业企业安全在线-梅墟街道20221114122715430556469.xlsx";
        System.out.println( name.substring(0,name.lastIndexOf("/")+1)+UrlEncoderUtils.encode(name.substring(name.lastIndexOf("/")+1)));

    }


}
